<template>
  <div>
    <Card dis-hover>
      <Form ref="queryForm">
        <Row style="margin-bottom:10px;">
          <Col span="24" style="text-align: right;">
            <Button :disabled="!hasPermission('Pages.Administration.Audits.Export')" icon="md-cloud-download"
                    style="margin-right:10px;"
                    type="info" @click="download">导出到EXCEL
            </Button>
            <Button icon="md-search" type="success" @click="getPage">搜索</Button>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="6">
            <FormItem prop="date" style="width:100%;margin-bottom:10px;">
              <DatePicker :editable="false" placeholder="选择时间范围" placement="bottom-start" split-panels
                          style="width:100%;" type="daterange" @on-change="dateChange"
                          @on-clear="handleClear"></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem prop="userName" style="width:100%;margin-bottom:10px;">
              <Input v-model="pageRequest.userName" clearable placeholder="用户名" @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem prop="serviceName" style="width:100%;margin-bottom:10px;">
              <Input v-model="pageRequest.serviceName" clearable placeholder="服务" @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem prop="methodName" style="width:100%;margin-bottom:10px;">
              <Input v-model="pageRequest.methodName" clearable placeholder="操作" @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
        </Row>
        <collapse-transition>
          <Row v-if="advancedSearch" :gutter="16">
            <Col span="6">
              <Row>
                <Col span="6">
                  <div style="width:100%;text-align:left;line-height:32px;color:#bcbcbc;">
                    持续时间
                  </div>
                </Col>
                <Col span="8">
                  <FormItem prop="duration" style="width:100%;margin-bottom:10px;">
                    <InputNumber v-model="pageRequest.minExecutionDuration" :max="99999" :min="0"
                                 clearable style="width:100%;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="2">
                  <div style="width:100%;text-align:center;line-height:32px;color:#bcbcbc;">
                    到
                  </div>
                </Col>
                <Col span="8">
                  <FormItem prop="duration" style="width:100%;margin-bottom:10px;">
                    <InputNumber v-model="pageRequest.maxExecutionDuration" :max="99999" :min="0"
                                 clearable style="width:100%;"></InputNumber>
                  </FormItem>
                </Col>
              </Row>
            </Col>
            <Col span="6">
              <FormItem prop="hasException" style="width:100%;">
                <Select v-model="pageRequest.hasException" clearable filterable
                        placeholder="选择执行状态" @on-clear="handleClear">
                  <Option :key="1" label="成功" value="false">
                    <Icon :size="16" :color="$config.color.success" type="md-checkmark-circle"></Icon>
                    <span style="margin-left:8px;">成功</span></Option>
                  <Option :key="2" label="失败" value="true">
                    <Icon :size="16" :color="$config.color.error" type="md-close-circle"></Icon>
                    <span style="margin-left:8px;">失败</span></Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem prop="browseInfo" style="width:100%;margin-bottom:10px;">
                <Input v-model="pageRequest.browserInfo" clearable placeholder="浏览器" @on-clear="handleClear"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem prop="clientIpAddress" style="width:100%;">
                <Input v-model="pageRequest.clientIpAddress" clearable placeholder="IP地址"
                       @on-clear="handleClear"></Input>
              </FormItem>
            </Col>

          </Row>
        </collapse-transition>
        <Row>
          <Col span="24">
            <Button v-show="advancedSearch" icon="ios-arrow-up" type="text"
                    @click="toggleClick">隐藏高级搜索
            </Button>
            <Button v-show="!advancedSearch" icon="ios-arrow-down" type="text"
                    @click="toggleClick">显示高级搜索
            </Button>
          </Col>
        </Row>
      </Form>
      <Table :columns="columns" :data="list" :loading="loading" border class="margin-top-10"
             no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" @on-sort-change="sortingChange"
             @on-row-dblclick="handleRowClick">
        <template slot="actions" slot-scope="{row}">
          <Button size="small" type="default" @click="display(row)">
            <Icon type="md-search"></Icon>
          </Button>
        </template>
      </Table>
      <Page :current="currentPage" :page-size="pageSize" :page-size-opts="[10,20,30,40]" :total="totalCount"
            class="margin-top-10"
            show-sizer show-total @on-change="pageChange"
            @on-page-size-change="pageSizeChange">

      </Page>
    </Card>
    <audit-modal v-if="auditModalMount" v-model="auditModalShow" :modal-data="auditData"></audit-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import PageRequest from '@/store/entities/page-request';
import CollapseTransition from '@/components/common/collapse-transition';
import Util from '@/lib/util';
import AuditModal from '@/views/administration/audit-log/modal/audit-modal.vue';
import AuditExpand from '@/components/expand/audit-expand.vue';


class PageAuditRequest extends PageRequest {
  filter: string = '';
  sorting: string = '';
  userName: string = '';
  serviceName: string = '';
  methodName: string = '';
  minExecutionDuration: number = 0;
  maxExecutionDuration: number = 65535;
  browserInfo: string = '';
  clientIpAddress: string = '';
  hasException: boolean;
  startTime: string = '1900-01-01 00:00:00';
  endTime: string = '2099-12-31 23:59:59';
}

@Component({
  components: {
    AuditExpand,
    AuditModal,
    CollapseTransition,
  },
})
export default class AuditLog extends AbpBase {
  name: string = 'AuditLog';

  advancedSearch: boolean = false;
  pageRequest: PageAuditRequest = new PageAuditRequest();

  auditModalMount: boolean = false;
  auditModalShow: boolean = false;
  auditData: any = {};

  columns = [
    {
      type: 'expand',
      width: 30,
      render: (h: any, params: any) => {
        return h(AuditExpand, {
          props: {
            row: params.row,
          },
        }, []);
      },
    },
    {
      title: '详情',
      align: 'center',
      width: 70,
      slot: 'actions',

    },
    {
      title: '状态',
      align: 'center',
      width: 70,
      render: (h: any, params: any) => {
        return h('Icon', {
          props: {
            type: params.row.exception ? 'md-close-circle' : 'md-checkmark-circle',
            color: params.row.exception ? this.$config.color.error : this.$config.color.success,
          },
        }, []);
      },

    },
    {
      title: '时间',
      align: 'center',
      key: 'executionTime',
      width: 180,
      sortable: this.$config.sorting.administration.audit,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime(params.row.executionTime));
      },

    },
    {
      title: '用户名',
      align: 'center',
      key: 'userName',
      width: 140,
      sortable: this.$config.sorting.administration.audit,

    },
    {
      title: '服务',
      align: 'center',
      key: 'serviceName',
      width: 300,
      sortable: this.$config.sorting.administration.audit,

    },
    {
      title: '操作',
      align: 'center',
      key: 'methodName',

      sortable: this.$config.sorting.administration.audit,

      mixWidth: 300,
    },
    {
      title: '持续时间',
      align: 'center',
      key: 'executionDuration',
      sortable: this.$config.sorting.administration.audit,
      width: 140,
      render: (h: any, params: any) => {
        return h('span', {}, params.row.executionDuration + 'ms');
      },
    },
  ];

  get list() {
    return this.$store.state.audit.list;
  }

  get loading() {
    return this.$store.state.audit.loading;
  }

  get pageSize() {
    return this.$store.state.audit.pageSize;
  }

  get totalCount() {
    return this.$store.state.audit.totalCount;
  }

  get currentPage() {
    return this.$store.state.audit.currentPage;
  }

  get excelFile() {
    return this.$store.state.audit.excelFile;
  }

  handleRowClick(row: any) {
    this.display(row);
  }

  display(row: any) {
    let temp = row;
    temp.executionTime = Util.getTime(temp.executionTime);
    this.auditData = temp;
    this.auditModalMount = true;
    this.$nextTick(() => {
      this.auditModalShow = true;
    });
  }

  dateChange(date: any[]) {
    this.pageRequest.startTime = (date[0] === '' ? '1900-01-01' : date[0]) + ' 00:00:00';
    this.pageRequest.endTime = (date[1] === '' ? '2099-12-31' : date[1]) + ' 23:59:59';

  }

  async download() {
    await this.$store.dispatch({
      type: 'audit/obtainAuditLogsToExcel',
      data: this.pageRequest,
    });
    if (this.hasPermission('Pages.Files.Download')) {
      Util.downloadWithToken('/api/File/DownloadTempFile?fileType=' + this.excelFile.fileType + '&fileToken=' + this.excelFile.fileToken + '&fileName=' + this.excelFile.fileName, this.excelFile.fileName, this.excelFile.fileType);
    } else {
      this.$Message.error({
        background: true,
        content: '下载失败，缺少文件下载权限',
        duration: this.$config.duration,
      });
    }
  }

  toggleClick() {
    this.advancedSearch = !this.advancedSearch;
  }

  async pageChange(page: number) {
    this.$store.commit('audit/setCurrentPage', page);
    await this.getPage();
  }

  async pageSizeChange(pageSize: number) {
    this.$store.commit('audit/setPageSize', pageSize);
    await this.getPage();
  }

  async sortingChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  async handleClear() {
    await this.getPage();
  }

  async getPage() {

    this.pageRequest.maxResultCount = this.pageSize;
    this.pageRequest.skipCount = (this.currentPage - 1) * this.pageSize;
    await this.$store.dispatch({
      type: 'audit/obtainAuditLogs',
      data: this.pageRequest,
    });
  }

  async created() {
    await this.getPage();
  }
}
</script>

<style lang="less" scoped>

</style>
